package https

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"
)

// 错误重试机制
func (c *CURL) retry() *CURL {
	// 如果未启用重试机制，则直接返回
	if c == nil || c.option.retry <= 0 {
		return c
	}
	if c.option.retry-1 > 0 {
		fmt.Println("第", c.option.retry-1, "次重试，时间间隔：", _default.retryList[c.option.retry-1])
	}
	if c.option.retry > 12 {
		// 超过重传次数，直接进行结果返回
		if c.option.retryUri != "" {
			b, _ := json.Marshal(c.option.reportList)
			go New(c.option.retryUri).
				WithOption(WithHttpsContinue(), WithNoLog()).
				ParamJson(map[string]any{
					"msg":    "FAILED",
					"report": string(b),
				}).
				PostJson()
		}
		return c
	}
	// 未到达重试次数的话
	if c.Error == nil && c.option.successContent != "" && !strings.Contains(c.Body, c.option.successContent) {
		c.Error = errors.New("返回结果中未找到 " + c.option.successContent + " 内容，重试中...")
	}
	if c.Error == nil {
		msg := "SUCCESS"
		if len(c.option.reportList) > 0 {
			// 重试后成功
			msg = "ATTEMPTED SUCCESS"
		}
		// 重试成功，则直接返回
		c.option.reportList = append(c.option.reportList, c.Body)
		b, _ := json.Marshal(c.option.reportList)
		go New(c.option.retryUri).
			WithOption(WithHttpsContinue(), WithNoLog()).
			ParamJson(map[string]any{
				"msg":    msg,
				"report": string(b),
			}).
			PostJson()
		return c
	}
	// 重试失败，则再次进行重试
	nc := c
	go func() {
		nc.option.reportList = append(nc.option.reportList, c.Error.Error())
		nc.Body = ""
		nc.Error = nil
		time.Sleep(_default.retryList[nc.option.retry-1])
		nc.option.retry++
		switch nc.option.method {
		case "get":
			nc.Get()
		case "post":
			nc.Post()
		case "postjson":
			nc.PostJson()
		}
	}()
	return c
}
